package cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1;

import org.apache.log4j.Logger;

import com.google.protobuf.InvalidProtocolBufferException;

import cn.com.sparkle.paxos.net.frame.FrameBody;
import cn.com.sparkle.paxos.net.netlayer.PaxosSession;
import cn.com.sparkle.paxos.net.protocolprocessor.ProtocolProcessor;
import cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1.PaxosMessages.MessagePackage;

public class ProtocolTransformProcessor implements ProtocolProcessor<FrameBody> {
	private final static Logger logger = Logger.getLogger(ProtocolTransformProcessor.class);
	private ProtocolProcessor<MessagePackage> next;

	public ProtocolTransformProcessor(ProtocolProcessor<MessagePackage> next) {
		this.next = next;
	}

	@Override
	public boolean receive(FrameBody t, PaxosSession session) {
		MessagePackage.Builder messagePackage = MessagePackage.newBuilder();
		try {
			messagePackage.mergeFrom(t.getBody());
			return next.receive(messagePackage.build(), session);
		} catch (InvalidProtocolBufferException e) {
			logger.error("fatal error", e);
			session.closeSession();
		}
		return true;
	}

	@Override
	public void onConnect(PaxosSession session) {
	}

	@Override
	public void onDisConnect(PaxosSession session) {
	}

}
